package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AspectGPT {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    private void autoPt(){
    }

    /**
     * 分别对insert与update方法进行注入
     * insert 注入createTime updateTime createUser updateUser
     *
     * update 注入updateTime updateUser
     * @param joinPoint
     */
    @Before("autoPt()")
    public void autoInjectTime(JoinPoint joinPoint) {
        log.info("before---------------");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);

        if (annotation == null) {
            log.warn("AutoFill annotation not found on method: " + signature.getName());
            return;
        }

        OperationType value = annotation.value();
        Object[] args = joinPoint.getArgs();

        if (args.length == 0) {
            log.warn("No arguments provided to the method.");
            return;
        }

        Object entity = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        try {
            if (value == OperationType.INSERT) {
                setFields(entity, currentId, now, true);
            } else if (value == OperationType.UPDATE) {
                setFields(entity, currentId, now, false);
            }
        } catch (Exception e) {
            log.error("Error while auto-filling fields: ", e);
        }
    }

    private void setFields(Object entity, Long currentId, LocalDateTime now, boolean isInsert) throws Exception {
        Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
        Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

        if (isInsert) {
            Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);

            setCreateUser.invoke(entity, currentId);
            setCreateTime.invoke(entity, now);
        }

        setUpdateUser.invoke(entity, currentId);
        setUpdateTime.invoke(entity, now);
    }
}
